package cn.airfei.netty.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @description:
 * @author: air
 * @create: 2020-12-30 14:58
 */
public class NIOFileChannel03 {
    public static void main(String[] args) throws IOException {
        // 创建一个输入流
        File file=new File("/home/air/Documents/test.text");
        FileInputStream fileInputStream = new FileInputStream(file);

        FileChannel inputStreamChannel = fileInputStream.getChannel();

        // 创建一个缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());

        int read = inputStreamChannel.read(byteBuffer);
        System.out.println(new String(byteBuffer.array()));

        FileOutputStream fileOutputStream = new FileOutputStream("/home/air/Documents/test3.text");


        // buffer 读写切换
        byteBuffer.flip();

        // 创建一个输出流
        FileChannel outputStreamChannel = fileOutputStream.getChannel();
        // 写入到channel
        outputStreamChannel.write(byteBuffer);


        // 关闭输入输出流
        fileOutputStream.close();
        fileInputStream.close();
    }
}
